package com.ziyucoding.springboot.labs.lab3.rocketmqdemo.producer;

import com.ziyucoding.springboot.labs.lab3.rocketmqdemo.message.Demo7Message;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 示例7的生产者（用于事务消息）
 *
 * @author ziyucoding
 * @date 2022-10-24
 **/
@Component
public class Demo7Producer {

    private static final String TX_PRODUCER_GROUP = "demo7-producer-group";

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送事务消息
     *
     * @param id
     * @return org.apache.rocketmq.client.producer.SendResult
     **/
    public SendResult sendMessageInTransaction(Integer id) {
        // 创建消息
        Message message = MessageBuilder.withPayload(new Demo7Message(id)).build();
        // 发送事务消息
        SendResult result = rocketMQTemplate.sendMessageInTransaction(TX_PRODUCER_GROUP, Demo7Message.TOPIC, message, id);
        return result;
    }

    @RocketMQTransactionListener(txProducerGroup = TX_PRODUCER_GROUP)
    public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

        private Logger logger = LoggerFactory.getLogger(getClass());

        @Override
        public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
            // ... local transaction process, return rollback, commit or unknown
            logger.info("[executeLocalTransaction][执行本地事务，消息：{} arg：{}]", msg, arg);
            return RocketMQLocalTransactionState.UNKNOWN;
        }

        @Override
        public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
            // ... check transaction status and return rollback, commit or unknown
            logger.info("[checkLocalTransaction][回查消息：{}]", msg);
            return RocketMQLocalTransactionState.COMMIT;
        }

    }
}
